import { Component, Fragment, useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { to } from "../../redux/reducer/router";
import { useNavigate, useLocation } from "react-router";
import { useSelector } from "react-redux";
import { Layout, Menu, Breadcrumb, Button, Message } from '@arco-design/web-react';
import { IconHome, IconCalendar, IconCaretRight, IconCaretLeft } from '@arco-design/web-react/icon';
import MySider from "./app/sider";
import MyHeader from "./app/header";
import { Outlet } from "react-router";
import '../../styles/app.css'
const Header = Layout.Header;
const Footer = Layout.Footer;
const Content = Layout.Content;


let topMenuReskeyFlag = '' // 顶级菜单分类
let topMenuReskeyChild = [] // 顶级菜单的孩子，也就是当前要显示在左侧页面的菜单
let flag = false // 用来保存顶级菜单的标志
function App(){
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const location = useLocation()
    const [menuState, setMenuState] = useState({
        isLeftNavMini: false, // 左侧导航菜单是否mini模式
        leftNav: [], // 左侧菜单列表
        topMenuReskey: 'platformManage', // 默认管理平台
        gMenuList: [], // 当前用户菜单列表
        idRenderChild: false, // 是否加载子组件
        isHideNav: false, // 是否隐藏左侧菜单
        isIframe: false, // 是否隐藏头部
    })
    // // 第一次挂载的时候：
    useEffect(()=>{
        console.log('token',sessionStorage.getItem('token'))
        if (sessionStorage.getItem('token') === null) {
            navigate('/login')
            return
        }
        if (sessionStorage.getItem('isLeftNavMini') === 'false') {
            setMenuState((menuState)=>{
                return{
                    ...menuState,
                    isLeftNavMini: false,
                }
            })
          }
        if (sessionStorage.getItem('isLeftNavMini') === 'true') {
            setMenuState((menuState)=>{
                return{
                    ...menuState,
                    isLeftNavMini: true
                }
            })
        }
        // 保证刷新时能够将刷新前的页面状态保存下来
        init(menuState, setMenuState, location)
    }, [])
    return(
        <Layout className='layout-collapse-demo'>
            <MySider menuState={menuState} setMenuState={setMenuState}></MySider>
            <Layout>
            <MyHeader></MyHeader>
            <Layout style={{ padding: '0 24px' }}>
                <Breadcrumb style={{ margin: '8px 0', }}>
                </Breadcrumb>
                <Content>
                    <Outlet></Outlet>
                </Content>
                <Footer>Footer</Footer>
            </Layout>
            </Layout>
        </Layout>
    )
}

function init(menuState,setMenuState, location) {
    const  { state }  = location
    if (state&&state.ticket) { // 如果是url路径带ticket的话，那么在当前页面做登录的初始化
    //   validateTickit(this.props.location, (res) => {
    //     this.setState({
    //       idRenderChild: true,
    //     })
    //   })
    } else if (state&&state.key) {
    //   const params = parseQueryString(window.location.href)
    //   loginByKey({ }, (res) => {
    //     sessionStorage.setItem('key', query.key)
    //     this.setState({
    //       idRenderChild: true,
    //     })
    //   })
    } else {
        // 获取菜单
        setMenuState((menuState)=>{
            return{
                ...menuState,
                gMenuList: JSON.parse(sessionStorage.getItem('gMenuList')) 
            }
        })
        // 定位菜单状态
        getMenuId(JSON.parse(sessionStorage.getItem('gMenuList')), location.pathname.replace('/', ''), menuState, setMenuState)
        // 初始化比较当前的顶级菜单属于哪个
        // 默认值为 platformManage
        const { topMenuReskey } = menuState
        // 一开始的时候sessionStorage的初始值为desk$
        if (topMenuReskey !== sessionStorage.getItem('topMenuReskey')) {
            setMenuState((menuState)=>{
                return{
                    ...menuState,
                    topMenuReskey: sessionStorage.getItem('topMenuReskey') 
                }
            })
        }
        setMenuState((menuState)=>{
            return{
                ...menuState,
                idRenderChild: true,
            }
        })
    }

    if (state&&(state.mode === 'iframe' || state.key)) {
        setMenuState((menuState)=>{
            return{
                ...menuState,
                isIframe: true
            }
        })
    } else {
        setMenuState((menuState)=>{
            return{
                ...menuState,
                isIframe: false,
            }
        })
    }
}

function getMenuId(nav, pathname, state, setState) {
    topMenuReskeyFlag = '' // 顶级菜单分类
    topMenuReskeyChild = [] // 顶级菜单的孩子，也就是当前要显示在左侧页面的菜单
    flag = false // 用来保存顶级菜单的标志
    // console.log(nav)
    if (nav && nav.length > 0) {
        compare(nav, pathname, state, setState)
    }
}

function compare(children, pathname, state, setState) {
    children.map((item) => {
      // console.log(item.resKey)
      // resKey中存在'platform'？？？
      if (item.resKey.indexOf('platform') > -1) {
        if (flag && (sessionStorage.getItem('topMenuReskey') !== 'set$')) {
          topMenuReskeyFlag = item.resKey
          topMenuReskeyChild = item.children
        }
      }
      const _resKey = `${item.resKey.replace(/[\$\.\?\+\^\[\]\(\)\{\}\|\\\/]/g, '\\$&').replace(/\*\*/g, '[\\w|\\W]+').replace(/\*/g, '[^\\/]+')}$`
      if (new RegExp(_resKey).test(pathname)) {
        // console.log(item.id)
        flag = true
        sessionStorage.setItem('menuId', item.id)
        // debugger
        sessionStorage.setItem('topMenuReskey', topMenuReskeyFlag)
        setState((state)=>{
            return{
                ...state, 
                menuId: item.id, 
                topMenuReskey: topMenuReskeyFlag }
        })
        return null
      } else if (item.children) {
        compare(item.children, pathname, state, setState)
      }
      return null
    })
}

export default App